﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using SYcwpb.Helpers;
using System.Collections.ObjectModel;
using SYcwpb.Models;
using SYcwpb.Commands;
using System.Windows.Input;
using SYcwpb.Access;
using System.Windows.Threading;
using System.Threading;
using SYcwpb.Views;
using System.Windows;
using SYcwpb.ViewModels.DataProvider;
using System.Collections.Specialized;
using System.Data;
using System.ComponentModel;


namespace SYcwpb.ViewModels
{
    public class BedRoomsViewModel : ViewModelBase
    {



        private BedRoomsAccess _bedRoomaccess = new BedRoomsAccess();
        private DriverTeamAccess _driverTeamAccess = new DriverTeamAccess(Convert.ToInt32(CONSTDATA.UserModel.Line));

        private List<BedRoomObject> UpdateList = new List<BedRoomObject>();
        private List<DriverRoom> lstDriverRoom = new List<DriverRoom>();

        private DataTable tomorrowInformDT;
        private DataTable informDT;


        private BedRoomsViewModel _viewModel = null;

        private BedRoomsView _view = new BedRoomsView();
        //保存路径
        private string filePath = "";
        private ShowTip tip;

        public bool FilterDriversResult = false;

        private SqlDataLayer sqlHelper = new SqlDataLayer();
        /// <summary>
        /// 今天的12点前，显示昨天的夜班司机公寓安排
        /// </summary>
        private string departTime = "02:00:00";

        private bool HasAutoSetRecord = false;

        private bool _isExporting = false;
        public bool IsExporting
        {
            get { return !_isExporting; }
            set
            {
                if (value == _isExporting)
                    return;

                _isExporting = value;

                OnPropertyChanged("IsExporting");
            }
        }


        private string _callHeadMin = "15";
        public string CallHeadMin
        {
            get { return _callHeadMin; }
            set
            {
                if (_callHeadMin == value)
                    return;

                _callHeadMin = value;

                OnPropertyChanged("CallHeadMin");
            }
        }

        private string _selectedDate;
        public string SelectedDate
        {
            get { return _selectedDate; }
            set
            {
                DateTime curT = Convert.ToDateTime(value);
                if (_selectedDate == curT.ToString("yyyy-MM-dd"))
                    return;
                _selectedDate = curT.ToString("yyyy-MM-dd");

                OnPropertyChanged("SelectedDate");
            }
        }

        private string _endDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
        public string EndDate
        {
            get { return _endDate; }
            set
            {
                DateTime curT = Convert.ToDateTime(value);
                if (_endDate == curT.ToString("yyyy-MM-dd"))
                    return;
                _endDate = curT.ToString("yyyy-MM-dd");

                OnPropertyChanged("EndDate");
            }
        }


        private BedRoomObjects _bedRoomsDetails;
        public BedRoomObjects BedRoomsDetails
        {
            get { return _bedRoomsDetails; }
            set
            {
                _bedRoomsDetails = value;

                OnPropertyChanged("BedRoomsDetails");
            }
        }
        private ObservableCollection<YBDriver> _unarrangeDriverList = new ObservableCollection<YBDriver>();
        public ObservableCollection<YBDriver> UnarrangeDriverList
        {
            get { return _unarrangeDriverList; }
            set
            {
                _unarrangeDriverList = value;

                OnPropertyChanged("UnarrangeDriverList");
            }
        }
        private ObservableCollection<YBDriver> _driverList = new ObservableCollection<YBDriver>();
        public ObservableCollection<YBDriver> DriverList
        {
            get { return _driverList; }
            set
            {
                _driverList = value;

                OnPropertyChanged("DriverList");
            }
        }

        private ICommand _autoSetRoomCommand;
        public ICommand AutoSetRoomCommand
        {
            get
            {
                if (null == _autoSetRoomCommand)
                    _autoSetRoomCommand = new RelayCommands(para => this.AutoSetRoomCommand_Method(), para => CanExecute());

                return _autoSetRoomCommand;
            }
        }

        private ICommand _saveCommand;
        public ICommand SaveCommand
        {
            get
            {
                if (null == _saveCommand)
                    _saveCommand = new RelayCommands(para => this.SaveCommand_Method(), para => CanExecute());

                return _saveCommand;
            }
        }

        //导出司机公寓安排结果
        private ICommand _exportResultCommand;
        public ICommand ExportResultCommand
        {
            get
            {
                if (null == _exportResultCommand)
                    _exportResultCommand = new RelayCommands(para => this.ExportResultCommand_Method(), para => CanExecute());
                return _exportResultCommand;
            }
        }

        private void ExportResultCommand_Method()
        {
            System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();
            fbd.ShowNewFolderButton = true;
            fbd.Description = "请选择排班表的保存路径";

            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                IsExporting = false;
                return;
            }
            filePath = fbd.SelectedPath;
            if (!filePath.EndsWith("\\"))
                filePath += "\\";

            _view.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ToExportResultExcel(ExportResultExcel));
            tip = new ShowTip();
            tip.ShowDialog();
        }

        //导出结果
        public delegate void ToExportResultExcel();
        public void ExportResultExcel()
        {
            IsExporting = true;
            //获取公寓安排结果
            DataTable sourceDataTable = GetExportResult();
            if (sourceDataTable.Rows.Count > 0)
            {
                try
                {

                    //初始化临时表
                    DataTable callPB = GetCallTable();
                    //初始化临时表数据
                    InitCallTable(ref callPB, sourceDataTable);

                    //把数据导出到Excel
                    string fileName = string.Format("司机公寓安排表_{0}.xlsx", DateTime.Now.AddDays(1).ToString("yyyy-MM-dd HH_mm_ss"));
                    OutExcel excel = new OutExcel();
                    //初始化表头
                    excel.ws.Cells[1, 1] = fileName.Split(' ')[0];
                    excel.UniteCells(excel.ws, 1, 1, 1, 6);//横向合并表头


                    excel.ws.Cells[2, 1] = "房间号";// A
                    excel.ws.Cells[2, 2] = "房间类别";//B
                    excel.ws.Cells[2, 3] = "床号";//C
                    excel.ws.Cells[2, 4] = "司机姓名";//D
                    excel.ws.Cells[2, 5] = "出勤时间";//E
                    excel.ws.Cells[2, 6] = "叫醒时间";//F

                    //设置表格样式
                    Excel.Range r1 = (Excel.Range)excel.ws.Cells[1, 1];
                    r1.Font.Size = 18;
                    r1.Font.Color = Excel.Constants.xlColor1;
                    excel.RefObjs.Push(r1);
                    r1 = null;
                    //((Excel.Range)excel.ws.Rows[2, System.Type.Missing]).Interior.ColorIndex = 20;
                    //列宽
                    for (int i = 2; i < 8; i++)
                    {
                        Excel.Range range = (Excel.Range)excel.ws.Columns[i, System.Type.Missing];
                        range.ColumnWidth = 14;
                        excel.RefObjs.Push(range);
                        range = null;
                    }
                    //行宽
                    string cell = sourceDataTable.Rows[0]["roomNum"].ToString();
                    int row = -1;
                    int sum = 0;
                    for (int i = 0; i < sourceDataTable.Rows.Count; i++)
                    {
                        Microsoft.Office.Interop.Excel.Range range = (Excel.Range)excel.ws.Rows[2 + i, System.Type.Missing];
                        excel.RefObjs.Push(range);
                        range.RowHeight = 18;
                        range = null;
                        //if (i % 2 == 0)
                        //{
                        //    ((Excel.Range)excel.ws.Rows[3 + i, System.Type.Missing]).Interior.ColorIndex = 19;
                        //}
                        //else
                        //{
                        //    ((Excel.Range)excel.ws.Rows[3 + i, System.Type.Missing]).Interior.ColorIndex = 39;
                        //}

                        //房间号合并
                        string tem = sourceDataTable.Rows[i]["roomNum"].ToString();
                        if (tem == cell)
                        {
                            row++;
                        }
                        if (tem != cell)
                        {

                            if (row > 0)
                            {
                                excel.UniteCells(excel.ws, 3 + sum, 1, 3 + sum + row, 1);

                            }
                            sum += row;
                            sum++;
                            row = 0;
                            cell = tem;
                        }
                        if (i == sourceDataTable.Rows.Count - 1 && row > 0)
                        {
                            excel.UniteCells(excel.ws, 3 + sum, 1, 3 + sum + row, 1);
                        }
                    }
                    //冻结单元格(方法没效果）
                    //Excel._Workbook _workBook = null;  
                    //Excel.Worksheet _workSheet = null;  
                    //Excel.Application _excelApplicatin = null;
                    //_excelApplicatin = new Excel.Application();
                    //_excelApplicatin.Visible = true;
                    //_excelApplicatin.DisplayAlerts = true;

                    //_workBook = _excelApplicatin.Workbooks.Add(Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
                    //_workSheet = (Microsoft.Office.Interop.Excel.Worksheet)_workBook.ActiveSheet;
                    //_workSheet.Name = "司机公寓安排";  
                    //// EXCEL操作(需要冻结的字段 按住ALT+W 再按F)  
                    //Excel.Range excelRange = _workSheet.get_Range(_workSheet.Cells[1, 6], _workSheet.Cells[2, 6]);
                    //excelRange.Select();
                    //_excelApplicatin.ActiveWindow.FreezePanes = true;  

                    excel.InsertTable(callPB, excel.ws, 3, 1);
                    excel.SaveAs(string.Format("{0}{1}", filePath, fileName));

                    excel.Close();
                    
                    excel.KillExcelProcess();

                    MessageBoxHelper.ShowTips(string.Format("导出 {0}  成功!", fileName));
                }
                catch (Exception ex)
                {
                    MessageBoxHelper.ShowError(string.Format("导出司机公寓安排表失败: {0}", ex.Message.ToString()));
                }

            }
            else
            {
                MessageBoxHelper.ShowTips("今天尚未保存有司机公寓安排结果，请确认保存数据后再导出。");
            }

            IsExporting = false;
            tip.Visibility = Visibility.Collapsed;
            tip.Close();
        }

        private DataTable GetExportResult()
        {
            //获取当天公寓安排结果数据表
            string sql = "select brm.brm_br_name as roomNum , br.br_sex as roomType,  brm.brm_bedindex as bedIndex ," +
                " brm.brm_username as DriverName, brm.brm_dutytime as dutyTime,brm_calltime as callTime " +
                " from BedRoomMaps brm left join BedRooms br on br.br_name = brm.brm_br_name " +
                " where brm.brm_date='" + SelectedDate + "' and brm_line=" + CONSTDATA.UserModel.Line + " order by br.br_priority";
            DataTable dr = sqlHelper.SelectDt(sql);

            return dr;
        }

        private DataTable GetCallTable()
        {
            DataTable callTable = new DataTable();

            DataColumn dc1 = new DataColumn("roomNum", System.Type.GetType("System.String"));   // 房间号
            DataColumn dc2 = new DataColumn("roomType", System.Type.GetType("System.String"));  //房间类型
            DataColumn dc3 = new DataColumn("bedIndex", System.Type.GetType("System.String"));  //床位号
            DataColumn dc4 = new DataColumn("DriverName", System.Type.GetType("System.String")); //司机
            DataColumn dc5 = new DataColumn("dutyTime", System.Type.GetType("System.String")); //出勤时间
            DataColumn dc6 = new DataColumn("callTime", System.Type.GetType("System.String")); //叫醒时间
            callTable.Columns.Add(dc1);
            callTable.Columns.Add(dc2);
            callTable.Columns.Add(dc3);
            callTable.Columns.Add(dc4);
            callTable.Columns.Add(dc5);
            callTable.Columns.Add(dc6);

            return callTable;
        }

        //初始化表中的数据
        private void InitCallTable(ref DataTable table, DataTable sourceDataTable)
        {
            for (int i = 0; i < sourceDataTable.Rows.Count; i++)
            {
                DataRow row = table.NewRow();
                row["roomNum"] = sourceDataTable.Rows[i]["roomNum"].ToString();
                row["roomType"] = sourceDataTable.Rows[i]["roomType"].ToString();
                row["bedIndex"] = sourceDataTable.Rows[i]["bedIndex"].ToString();
                row["DriverName"] = sourceDataTable.Rows[i]["DriverName"].ToString();
                row["dutyTime"] = sourceDataTable.Rows[i]["dutyTime"].ToString();
                row["callTime"] = sourceDataTable.Rows[i]["callTime"].ToString();

                table.Rows.Add(row);
            }
        }
        #region 添加非夜班司机到公寓功能的属性

        private string _dName;
        public string DName
        {
            get { return _dName; }
            set
            {
                if (value == _dName)
                    return;

                _dName = value;
                OnPropertyChanged("DName");
            }
        }
        private List<string> _lst;
        public List<string> Lst
        {
            get { return _lst; }
            set
            {
                if (_lst != value)
                {
                    _lst = value;
                    OnPropertyChanged("Lst");
                }
            }
        }
        public ObservableCollection<BedRoomsModel> _bedRoomCollections;
        public ObservableCollection<BedRoomsModel> BedRoomCollections
        {
            get { return _bedRoomCollections; }
            set
            {
                _bedRoomCollections = value;
                OnPropertyChanged("BedRoomCollections");
            }
        }

        private BedRoomsModel _selectedRoom;
        public BedRoomsModel SelectedRoom
        {
            get { return _selectedRoom; }
            set
            {
                _selectedRoom = value;

                OnPropertyChanged("SelectedRoom");
            }
        }

        private int _bedIndex;
        public int BedIndex
        {
            get { return _bedIndex; }
            set
            {
                _bedIndex = value;

                OnPropertyChanged("BedIndex");
            }
        }

        private string _dutyTime;

        private string _callTime;

        private bool _addNotMorDriverEnabled = false;
        public bool AddNotMorDriverEnabled
        {
            //get { return _addNotMorDriverEnabled; }
            get { return true; }
            set
            {
                _addNotMorDriverEnabled = value;

                OnPropertyChanged("AddNotMorDriverEnabled");
            }
        }

        private ICommand _addNotMorDriverCommand;
        public ICommand AddNotMorDriverCommand
        {
            get
            {
                if (_addNotMorDriverCommand == null)
                    _addNotMorDriverCommand = new RelayCommands(para => this.AddNotMorDriverCommand_Method());

                return _addNotMorDriverCommand;
            }
        }
        #endregion


        public BedRoomsViewModel()
        {
            InitSelectedDate();

            InitBedRoomObjects();
            PriorityCount();

            if (SelectedDate == DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"))
                InitYbDriverList();
        }

        private void PriorityCount()
        {
            string getCount = "select COUNT(*) from BedRooms where br_line = '" + Convert.ToInt32(CONSTDATA.UserModel.Line) + "'";
            DataTable dt = sqlHelper.SelectDt(getCount);
            int total = 0;
            if (dt.Rows.Count > 0)
            {
                total = Convert.ToInt32(dt.Rows[0][0].ToString());
            }

            _lst = new List<string>();
            for (int i = 0; i < total; i++)
            {
                _lst.Add(Convert.ToString(i + 1));
            }


        }
        private void InitSelectedDate()
        {
            if (DateTime.Now.ToString("HH:mm:ss").CompareTo(departTime) < 1)
                SelectedDate = DateTime.Now.ToString("yyyy-MM-dd");
            else
                SelectedDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
        }
        private void BedRoomObjectPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            BedRoomObject bed = sender as BedRoomObject;
            if (e.PropertyName == "TheDriver")
            {
                if (bed.TheDriver == null)
                {
                    bed.CanCelCall = BedRoomObject.CANCEL_CALL;
                }
                else if(informDT!=null)
                {
                    string name = bed.TheDriver.DriverName;
                    string time;

                    string str = " deleted=1and Callvoice like '%" + name + "%'";

                    if (!string.IsNullOrEmpty(bed.TheDriver.DutyTime))
                    {
                        time = Convert.ToDateTime(bed.TheDriver.DutyTime).ToString("HH:mm");
                        str += "and callvoice like '%" + time + "%' ";
                    }
                    DataRow[] rows = informDT.Select(str); ;
                    if (rows.Length > 0)
                    {
                        bed.CanCelCall = BedRoomObject.CANCELED;
                    }
                }
            }
        }
        public void InitBedRoomObjects()
        {
            BedRoomsDetails = new BedRoomObjects();

            DataTable roomDT = _bedRoomaccess.GetRooms();
            informDT = _bedRoomaccess.GetInform(DateTime.Now);
            

            if (null == roomDT || roomDT.Rows.Count < 1)
                return;

            BedRoomCollections = new ObservableCollection<BedRoomsModel>();
            lstDriverRoom.Clear();
            for (int i = 0; i < roomDT.Rows.Count; i++)
            {


                DriverRoom driverRoom = new DriverRoom();
                driverRoom.ID = roomDT.Rows[i]["ID"].ToString();
                driverRoom.br_name = roomDT.Rows[i]["br_name"].ToString();
                driverRoom.br_sex = roomDT.Rows[i]["br_sex"].ToString();
                // driverRoom.br_bed_avai =Convert.tp roomDT.Rows[i]["br_bed_avai"].ToString();
                driverRoom.br_bed_avai = Convert.ToInt32(roomDT.Rows[i]["br_bed_avai"].ToString());
                lstDriverRoom.Add(driverRoom);
                string roomName = roomDT.Rows[i]["br_name"].ToString();
                int bedCount = Convert.ToInt32(roomDT.Rows[i]["br_bed_avai"]);

                BedRoomsModel model = BedRoomsModel.GetBedRoomsModel(roomName, bedCount);
                BedRoomCollections.Add(model);

                string roomType = roomDT.Rows[i]["br_sex"].ToString();
                for (int k = 1; k <= bedCount; k++)
                {
                    BedRoomObject bed = new BedRoomObject();
                    //注册属性改变事件
                    bed.PropertyChanged += new PropertyChangedEventHandler(BedRoomObjectPropertyChanged);

                    bed.RoomName = roomName;
                    bed.RoomType = roomType;
                    bed.BedIndex = k.ToString();
                    bed.CanCelCall = BedRoomObject.CANCEL_CALL;
                    BedRoomsDetails.Add(bed);
                }
            }
            BedRoomsDetails.itemEndEdit += new ItemEndEditEventHandler(BedRoomsDetails_itemEndEdit);
            BedRoomsDetails.CollectionChanged += new NotifyCollectionChangedEventHandler(BedRoomsDetails_CollectionChanged);

            InitRoomMaps();

            if (SelectedDate == DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") && HasAutoSetRecord)
            {
                AddNotMorDriverEnabled = true;
            }
            else
                AddNotMorDriverEnabled = false;
        }

        void BedRoomsDetails_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {

        }

        void BedRoomsDetails_itemEndEdit(System.ComponentModel.IEditableObject sender)
        {
        }

        private bool CanExecute()
        {
            return SelectedDate == DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
        }

        private void SaveCommand_Method()
        {
            bool record = _bedRoomaccess.GetTodayBedRoomRecord(SelectedDate);

            if (record && MessageBoxHelper.ConfirmYesNo("是否执行更新？") == false)
            {
                return;
            }

            if (_bedRoomaccess.UpdateBedRooms(BedRoomsDetails, record, SelectedDate))
            {
                MessageBoxHelper.ShowTips("保存夜班司机公寓安排成功！");

                HasAutoSetRecord = true;
            }
            else
                MessageBoxHelper.ShowError("保存夜班司机公寓安排失败，请重试！！");
        }

        private void AutoSetRoomCommand_Method()
        {
            if (SelectedDate != DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"))
            {
                MessageBoxHelper.ShowError("请选择正确日期后重试！（自动排公寓功能仅限于当天）");
                return;
            }

            if (!GlobalVariables.IsNumberic(CallHeadMin))
            {
                MessageBoxHelper.ShowError("请输入有效的提前时间！！");
                return;

            }
            else if (Convert.ToInt32(CallHeadMin) < 0 || Convert.ToInt32(CallHeadMin) > 60)
            {
                MessageBoxHelper.ShowError("提前时间范围在60分钟以内，请确认！！！");
                return;
            }

            if (InitYbDriverList())
            {
                if (DriverList.Count < 1)
                {
                    MessageBoxHelper.ShowError("获取司机信息失败！");
                    return;
                }
                FilterDriversResult = false;
                FilterDrivers fd = new FilterDrivers(this);
                fd.ShowDialog();
                if (!FilterDriversResult)
                    return;

                if (CONSTDATA.IsNewSetRoom)
                    //SetRoom1();
                    SetRoom2();
                else
                    SetRoom();
                //
                AddNotMorDriverEnabled = true;
            }

        }

        /// <summary>
        /// 如果已经有今天的夜班司机安排，则取出数据初始化BedRoomDetails
        /// </summary>
        private void InitRoomMaps()
        {
            if (!_bedRoomaccess.GetTodayBedRoomRecord(SelectedDate))
            {
                HasAutoSetRecord = false;
                return;
            }
            
            HasAutoSetRecord = true;

            DataTable roomMapsDT = _bedRoomaccess.GetRoomMaps(SelectedDate);

            if (null == roomMapsDT || roomMapsDT.Rows.Count < 1)
                return;

            for (int i = 0; i < roomMapsDT.Rows.Count; i++)
            {
                string driverName = roomMapsDT.Rows[i]["brm_username"].ToString();
                if (string.IsNullOrEmpty(driverName))
                    continue;

                string roomName = roomMapsDT.Rows[i]["brm_br_name"].ToString();
                string bedIndex = roomMapsDT.Rows[i]["brm_bedindex"].ToString();

                YBDriver driver = new YBDriver();
                driver.DriverName = driverName;
                driver.DutyTime = roomMapsDT.Rows[i]["brm_dutytime"].ToString();
                driver.CallTime = roomMapsDT.Rows[i]["brm_calltime"].ToString();

                for (int k = 0; k < BedRoomsDetails.Count; k++)
                {
                    if (BedRoomsDetails[k].RoomName == roomName && BedRoomsDetails[k].BedIndex == bedIndex)
                    {
                        BedRoomsDetails[k].TheDriver = driver;
                        string name = driver.DriverName;
                        string time;

                        string str = "  deleted=1 and Callvoice like '%" + name + "%'";

                        if (!string.IsNullOrEmpty(driver.DutyTime))
                        {
                            time = Convert.ToDateTime(driver.DutyTime).ToString("HH:mm");
                            str += "and callvoice like '%" + time + "%'";
                        }
                        DataRow[] rows = informDT.Select(str); ;
                        if (rows.Length > 0)
                        {
                            BedRoomsDetails[k].CanCelCall = BedRoomObject.CANCELED;
                        }
                        break;
                    }
                }
            }

        }
        private void arrangeCombineRoom(List<YBDriver> dlist,List<BedRoomObject> brlist,DriverRoom room)
        {
            for (int k = 0; k < dlist.Count &&room.br_bed_avai>0; k++)
            {
                YBDriver driver = dlist[k];
                RoomBed bed = new RoomBed();
                bed.br_bed_num = brlist[room.br_bed_num].BedIndex;
                brlist[room.br_bed_num].TheDriver = driver;
                room.beds.Add(bed);
                driver.IshasRoom = true;
                room.br_bed_num++;
            }
        }
        /// <summary>
        /// 获取时间差
        /// </summary>
        /// <returns></returns>
        private int getTD(string time1,string time2) 
        { 
            if(string.IsNullOrEmpty(time1)||string.IsNullOrEmpty(time2))
                return 0;
            string[] timeSplit1,timeSplit2;
            timeSplit1 = time1.Split(':');
            timeSplit2 = time2.Split(':');
            return Math.Abs((Convert.ToInt32(timeSplit1[0]) - Convert.ToInt32(timeSplit2[0])) * 60 +
                (Convert.ToInt32(timeSplit1[1])-Convert.ToInt32(timeSplit2[1])));
        }

        /// <summary>
        /// 在剩余房间里查找最合适（出勤时间最接近）的房间进行匹配
        /// </summary>
        /// <param name="arranged"></param>
        /// <param name="bedRoomDetails"></param>
        /// <param name="dlist"></param>
        /// <param name="unarrangedDriverList"></param>
        private void arrangeMinDTRoom(bool arranged, List<BedRoomObject> bedRoomDetails, List<YBDriver> dlist, List<YBDriver> unarrangedDriverList) 
        {
            int matchRoomIndex = -1;
            int minTD = 0;
            for (int i = 0; !arranged && i < lstDriverRoom.Count; i++)
            {
                DriverRoom room = lstDriverRoom[i];
                List<BedRoomObject> brlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == room.br_name; });
                if (room.br_bed_avai>0&&dlist.Count <= room.br_bed_avai - room.br_bed_num && dlist[0].Sex == room.br_sex)
                {
                    if (room.br_bed_num == 0)
                    {
                        matchRoomIndex = i;
                        arranged = true;
                        arrangeCombineRoom(dlist, brlist, room);
                        break;
                    }
                    
                    if (matchRoomIndex == -1)
                    {
                        matchRoomIndex = i;
                        minTD = getTD(dlist[0].DutyTime, brlist[0].TheDriver.DutyTime);
                        continue;
                    }
                    BedRoomObject bedRoomPbject = bedRoomDetails.Find(delegate(BedRoomObject bro) { return bro.RoomName == room.br_name; });
                    if (!string.IsNullOrEmpty(brlist[0].TheDriver.DutyTime))
                    {
                        int td = getTD(dlist[0].DutyTime, brlist[0].TheDriver.DutyTime);
                        if (minTD > td)
                        {
                            minTD = td;
                            matchRoomIndex = i;
                        }
                        continue;
                    }
                    else
                    {
                        arranged = true;
                        arrangeCombineRoom(dlist, brlist, room);
                        break;
                    }
                }
            }
            if (!arranged)
            {
                if (matchRoomIndex == -1)
                    unarrangedDriverList.AddRange(dlist);
                else
                {
                    var brlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == lstDriverRoom[matchRoomIndex].br_name; });
                    arrangeCombineRoom(dlist, brlist, lstDriverRoom[matchRoomIndex]);
                }
            }
        }

        private void ArrangeDisperseCombine(List<YBDriver> unarrangedDriverList, List<BedRoomObject> bedRoomDetails)
        {
            //这里将组打散安排入宿
            for (int i = 0; i < unarrangedDriverList.Count; i++)
            {
                YBDriver driver = unarrangedDriverList[i];
                for (int p = lstDriverRoom.Count - 1; p >= 0; p--)
                {

                    DriverRoom room = lstDriverRoom[p];
                    List<BedRoomObject> brlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == room.br_name; });
                    if (room.br_bed_avai > room.br_bed_num && room.br_sex == driver.Sex
                        && room.br_bed_avai > 0)
                    {
                        RoomBed bed = new RoomBed();
                        bed.br_bed_num = brlist[room.br_bed_num].BedIndex;
                        brlist[room.br_bed_num].TheDriver = driver;
                        room.beds.Add(bed);

                        driver.IshasRoom = true;
                        room.br_bed_num++;
                        break;
                    }
                }
            }
        }
        /// <summary>
        /// 如果宿舍有空位，则前移司机
        /// 注意：前移的单位是司机，而不是司机组
        /// </summary>
        /// <param name="roomIndex"></param>
        /// <param name="nextRoomIndex"></param>
        private void ForwordDriver(int roomIndex,int nextRoomIndex) 
        {
            if (nextRoomIndex >= lstDriverRoom.Count)
                return;
            

            DriverRoom room = lstDriverRoom[roomIndex];
            DriverRoom nextRoom = lstDriverRoom[nextRoomIndex];

            var bedRoomDetails = BedRoomsDetails.ToList();

            if (room.br_sex == nextRoom.br_sex&&
                lstDriverRoom[nextRoomIndex].br_bed_avai > 0)
            {

                List<BedRoomObject> brlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == room.br_name; });
                List<BedRoomObject> nbrlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == nextRoom.br_name; });
                int p = 0;
                for (int i = room.br_bed_num; i < room.br_bed_avai && nextRoom.br_bed_num>0; i++)
                {
                    //brlist[i] = nbrlist[i - room.br_bed_num - 1];
                    
                    if(brlist[i].TheDriver==null){
                        brlist[i].TheDriver = nbrlist[p].TheDriver;
                        nbrlist[p].TheDriver = null;
                        room.br_bed_num++;
                        nextRoom.br_bed_num--;
                        p++;
                    }
                }
                if (p > 0)
                {
                    for (int i = 0; p < nextRoom.br_bed_avai; i++, p++)
                    {
                        nbrlist[i].TheDriver = nbrlist[p].TheDriver;
                        nbrlist[p].TheDriver = null;
                    }
                }
                
                
                roomIndex = nextRoomIndex;
                nextRoomIndex++;
            }
            else
            {
                nextRoomIndex++;
            }
            ForwordDriver(roomIndex, nextRoomIndex);
        }
        private void ArrangeDisperseCombine2(List<YBDriver> unarrangedDriverList, List<BedRoomObject> bedRoomDetails)
        {
            
            List<YBDriver> manDriverList = new List<YBDriver>();
            List<YBDriver> womanDriverList = new List<YBDriver>();
            //这些都是倒叙添加的
            List<DriverRoom> manDroomList = new List<DriverRoom>();
            List<DriverRoom> womanDroomList = new List<DriverRoom>();

            int manChaifenIndex = -1, manBadChaifenIndex=-1, womanChaifenIndex = -1,womanBadChaifenIndex=-1;
            int mlindex = -1, wlindex = -1,mbadindex=-1,wbadindex=-1;
            int manLastEmptyCount=0, womanLastEmptyCount = 0;
            foreach (var d in unarrangedDriverList)
            {
                if (d.Sex == "男")
                    manDriverList.Add(d);
                else
                    womanDriverList.Add(d);
            }

            
            for (int i = lstDriverRoom.Count-1; i >= 0; i--)
            {
                var r = lstDriverRoom[i];
                //if (r.br_bed_avai <= 0)
                //    continue;
                if (lstDriverRoom[i].br_sex == "男")
                {
                    if (manDriverList.Count == 0)
                        continue;
                    manLastEmptyCount += r.br_bed_avai - r.br_bed_num;
                    manDroomList.Add(r);
                    bool tiaojian=r.br_bed_avai > 0 &&manChaifenIndex == -1;

                    manBadChaifenIndex = i;
                    mbadindex = manDroomList.Count - 1;
                    if ((tiaojian && manLastEmptyCount >= manDriverList.Count) || (tiaojian && i == 0) || (tiaojian && lstDriverRoom[i - 1].br_sex != r.br_sex))
                    {
                        manChaifenIndex = i;
                        mlindex = manDroomList.Count - 1;
                    }
                }
                else
                {
                    if (womanDriverList.Count == 0)
                        continue;
                    womanLastEmptyCount += r.br_bed_avai - r.br_bed_num;
                    womanDroomList.Add(r);
                    bool tiaojian = r.br_bed_avai > 0 && womanChaifenIndex == -1;
                    womanBadChaifenIndex = i;
                    wbadindex = womanDroomList.Count - 1;
                    if ((tiaojian && womanLastEmptyCount >= womanDriverList.Count) || (tiaojian && i == 0) || (tiaojian && lstDriverRoom[i - 1].br_sex != r.br_sex))
                    {
                        womanChaifenIndex = i;
                        wlindex = womanDroomList.Count - 1;
                    }
                }
            }
            if (manChaifenIndex == -1 && manDriverList.Count>0)
            {
                manChaifenIndex = manBadChaifenIndex;
                mlindex = mbadindex;
            }
            if (womanChaifenIndex == -1&&womanDriverList.Count>0)
            {
                womanChaifenIndex = womanBadChaifenIndex;
                wlindex = wbadindex;
            }



            for (int i = manChaifenIndex; i < lstDriverRoom.Count && i >= 0; i++)
            {
                DriverRoom room = lstDriverRoom[i];
                if (room.br_bed_avai > room.br_bed_num&&room.br_sex=="男")
                {
                    ForwordDriver(i, i + 1);
                }
            }
            for (int i = womanChaifenIndex; i < lstDriverRoom.Count&&i>=0; i++)
            {
                DriverRoom room = lstDriverRoom[i];
                if (room.br_bed_avai > room.br_bed_num&&room.br_sex=="女")
                {
                    ForwordDriver(i, i + 1);
                }
            }
            for (int i = 0; i < manDriverList.Count;i++ )
            {
                YBDriver driver = manDriverList[i];
                for (int p = mlindex; p >= 0;p-- )
                {
                    DriverRoom room = manDroomList[p];
                    List<BedRoomObject> brlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == room.br_name; });
                    if (room.br_bed_avai > room.br_bed_num && room.br_sex == driver.Sex
                        && room.br_bed_avai > 0)
                    {
                        RoomBed bed = new RoomBed();
                        bed.br_bed_num = brlist[room.br_bed_num].BedIndex;
                        brlist[room.br_bed_num].TheDriver = driver;
                        room.beds.Add(bed);
                        driver.IshasRoom = true;
                        room.br_bed_num++;
                        break;
                    }
                }
            }
            for (int i = 0; i < womanDriverList.Count; i++)
            {
                YBDriver driver = womanDriverList[i];
                for (int p = wlindex; p >= 0; p--)
                {
                    DriverRoom room = womanDroomList[p];
                    List<BedRoomObject> brlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == room.br_name; });
                    if (room.br_bed_avai > room.br_bed_num && room.br_sex == driver.Sex
                        && room.br_bed_avai > 0)
                    {
                        RoomBed bed = new RoomBed();
                        bed.br_bed_num = brlist[room.br_bed_num].BedIndex;
                        brlist[room.br_bed_num].TheDriver = driver;
                        room.beds.Add(bed);
                        driver.IshasRoom = true;
                        room.br_bed_num++;
                        break;
                    }
                }
            }


        }
        private void ArrangeDisperseCombine1(List<YBDriver> unarrangedDriverList, List<BedRoomObject> bedRoomDetails)
        {
            bool hasMan = false;
            bool hasWoman = false;
            foreach (var d in unarrangedDriverList)
            {
                if (d.Sex == "男")
                    hasMan = true;
                else
                    hasWoman = true;
            }

            //这里将组打散安排入宿
            for (int i = 0; i < lstDriverRoom.Count; i++)
            {
                DriverRoom room = lstDriverRoom[i];
                if ((room.br_sex == "男" && hasMan) ||
                    (room.br_sex == "女" && hasWoman))
                {
                    if (room.br_bed_avai > room.br_bed_num)
                    {
                        ForwordDriver(i, i + 1);
                    }
                }

            }

            for (int i = 0; i < unarrangedDriverList.Count; i++)
            {
                YBDriver driver = unarrangedDriverList[i];
                for (int p = 0; p < lstDriverRoom.Count - 1; p++)
                {

                    DriverRoom room = lstDriverRoom[p];
                    List<BedRoomObject> brlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == room.br_name; });
                    if (room.br_bed_avai > room.br_bed_num && room.br_sex == driver.Sex
                        && room.br_bed_avai > 0)
                    {
                        RoomBed bed = new RoomBed();
                        bed.br_bed_num = brlist[room.br_bed_num].BedIndex;
                        brlist[room.br_bed_num].TheDriver = driver;
                        room.beds.Add(bed);

                        driver.IshasRoom = true;
                        room.br_bed_num++;
                        break;
                    }
                }
            }

        }
        private List<YBDriver> PopCombine(List<List<YBDriver>> list)
        {
            //0为不安排出勤时间相近的组同一房间
            

            if (list.Count > 0)
            {
                var item = list[0];
                list.RemoveAt(0);
                return item;
            }
            return null;
        }
        private void arrangeMinDTRoom1(List<List<YBDriver>> combineList)
        {
            var bedRoomDetails = BedRoomsDetails.ToList();
            var unarrangedDriverList = new List<YBDriver>();
            for(int k=0;k<combineList.Count;k++)
            {
                List<YBDriver> dlist=combineList[k];
                //判断房间是否空房，如果还没安排则对房间进行安排，否则对下一组司机进行安排

                //变量指示司机组是否已经找到匹配的房间
                bool isArranged = false;


                for (int i = 0; i < lstDriverRoom.Count; i++)
                {
                    DriverRoom room = lstDriverRoom[i];
                    if (room.br_bed_num == 0 && dlist[0].Sex == room.br_sex && room.br_bed_avai > 0&&dlist.Count<=room.br_bed_avai)
                    {
                        room.CombineListIndex.Enqueue(k);
                        List<BedRoomObject> brlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == room.br_name; });
                        arrangeCombineRoom(dlist, brlist, room);
                        isArranged = true;
                        break;
                    }
                }
                //如未找到空房，而且该房间能容纳该组人数，则将后面房间的人数全部往前移
                int rindex = 0;

                if (!isArranged)
                {

                    var result = ForwordCombine(rindex, rindex + 1, -1, k, combineList);
                    //当结果返回为null时，表示 
                    if (result != null)
                    {
                        result.CombineListIndex.Enqueue(k);
                        List<BedRoomObject> brlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == result.br_name; });
                        arrangeCombineRoom(dlist, brlist, result);
                    }
                    else
                    {
                        unarrangedDriverList.AddRange(dlist);
                    }
                }



            }
            if(unarrangedDriverList.Count>0)
                ArrangeDisperseCombine2(unarrangedDriverList, bedRoomDetails);

            List<YBDriver> lstLastNoRoomDriver = new List<YBDriver>(DriverList.ToList()).FindAll(delegate(YBDriver info)
            {
                if (info.IshasRoom == false)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });

            //将同房的司机组的出勤时间如果相差不到7分钟，则将叫醒时间改为一致
            //for (int i = 0; i < lstDriverRoom.Count;i++ )
            //{
            //    var room = lstDriverRoom[i];
            //    List<BedRoomObject> brlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == room.br_name; });
            //    string firstCallTime = null;
            //    for (int j = 0; j < room.br_bed_num; j++)
            //    {
            //        if (j == 0)
            //            firstCallTime = brlist[j].TheDriver.CallTime;
            //        else
            //        {
            //            if (firstCallTime != brlist[j].TheDriver.CallTime)
            //            {
            //                int td = getTD(firstCallTime, brlist[j].TheDriver.CallTime);
            //                if (td != 0 && td < 7)
            //                {
            //                    brlist[j].TheDriver.CallTime = firstCallTime;
            //                }
            //            }
            //        }
            //    }
            //}

            if (lstLastNoRoomDriver.Count > 0)
            {
                List<string> lst = new List<string>();
                lst.Add("以下司机未安排到房间：");
                foreach (YBDriver noRoomDriver in lstLastNoRoomDriver)
                {
                    lst.Add(noRoomDriver.DriverName);
                }
                MessageBoxHelper.ShowError(lst);
            }
        }
        /// <summary>
        /// 前移司机组
        /// </summary>
        /// <param name="rindex">要前移的房间索引</param>
        /// <param name="nrindex">前移的房间索引</param>
        /// <param name="lrindex">最后前移的房间索引</param>
        /// <param name="driverIndex"></param>
        /// <param name="combineList"></param>
        /// <returns></returns>
        private DriverRoom ForwordCombine(int rindex, int nrindex,int lrindex, int driverIndex, List<List<YBDriver>> combineList)
        {
            DriverRoom room = lstDriverRoom[rindex];
            List<YBDriver> dlist = combineList[driverIndex];
            var bedRoomDetails = BedRoomsDetails.ToList();
            

            if (lstDriverRoom[nrindex].br_sex == dlist[0].Sex
                && combineList[driverIndex][0].Sex == room.br_sex
                && lstDriverRoom[nrindex].br_bed_avai>0
                && lstDriverRoom[nrindex].CombineListIndex.Count > 0
                && combineList[driverIndex].Count <= lstDriverRoom[nrindex].br_bed_avai - lstDriverRoom[nrindex].br_bed_num + combineList[lstDriverRoom[nrindex].CombineListIndex.Peek()].Count
                //&& driverIndex < combineList.Count
                //&& dlist.Count <= room.br_bed_avai - room.br_bed_num
                && combineList[lstDriverRoom[nrindex].CombineListIndex.Peek()].Count <= room.br_bed_avai - room.br_bed_num
                )
            {
                int dindex = lstDriverRoom[nrindex].CombineListIndex.Peek();
                List<YBDriver> ndlist = combineList[dindex];
                DriverRoom nextRoom = lstDriverRoom[nrindex];
                List<BedRoomObject> brlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == room.br_name; });
                arrangeCombineRoom(ndlist, brlist, room);
                dindex = nextRoom.CombineListIndex.Dequeue();
                room.CombineListIndex.Enqueue(dindex);
                rindex = nrindex;
                //if (combineList[driverIndex].Count <= lstDriverRoom[nrindex].br_bed_avai - lstDriverRoom[nrindex].br_bed_num)
                lrindex = nrindex;
                //如果被前移的房间还有其他组司机，则将它们补上空位
                List<BedRoomObject> nbrlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == nextRoom.br_name; });
                if (nextRoom.br_bed_num > ndlist.Count )
                {
                    //nextRoom.br_bed_num = 0;
                    int br_bed_num=0;
                    for (int bindex = ndlist.Count - 1; bindex < nextRoom.br_bed_num;bindex++ )
                    {
                        nbrlist[bindex - ndlist.Count + 1].TheDriver = nbrlist[bindex].TheDriver;
                        nbrlist[bindex].TheDriver = null;
                        br_bed_num++;
                    }
                    nextRoom.br_bed_num = br_bed_num;
                }
                else
                {
                    for (int bindex = 0 ; bindex < nextRoom.br_bed_num; bindex++)
                    {
                        nbrlist[bindex].TheDriver = null;
                        
                    }
                    nextRoom.br_bed_num = 0;
                }

            }
            else if (combineList[driverIndex][0].Sex == room.br_sex
                && room.br_bed_avai-room.br_bed_num>0 )
            {

            }
            else
            {
                rindex++;
            }
            //递归终止条件：循环到最后一个房间，即没有可以前移的房间和司机组了
            if (nrindex + 1 < lstDriverRoom.Count)
            {
                return ForwordCombine(rindex, ++nrindex, lrindex,driverIndex, combineList);
            }
            else if (lrindex != -1)
            {
                return lstDriverRoom[lrindex];
            }
            else
            {
                return null;
            }
        }
        private void InitBedRoom()
        {
            foreach (BedRoomObject bed in BedRoomsDetails)
            {
                bed.TheDriver = null;
            }
            foreach (var room in lstDriverRoom)
            {
                room.br_bed_num = 0;
                room.CombineListIndex.Clear();
                room.beds.Clear();
            }
            foreach (var item in BedRoomsDetails)
            {
                item.TheDriver = null;
            }
        }
        /// <summary>
        /// 极端排法，不考虑房间问题，只管按顺序把床位排下来
        /// </summary>
        private void SetRoom3() 
        {
            InitBedRoom();

                
                foreach (var driver in DriverList)
                {
                    foreach (var bedroom in BedRoomsDetails)
                    {
                        DriverRoom drroom = lstDriverRoom.Find(delegate(DriverRoom room) { return room.br_name == bedroom.RoomName; });
                        if (bedroom.TheDriver!=null||drroom.br_bed_avai == 0 || 
                            drroom.br_bed_avai <= drroom.br_bed_num||drroom.br_sex!=driver.Sex)
                            continue;

                        drroom.ListDriverComand.Add(driver.driverCommandID);
                        drroom.br_bed_num++;
                        RoomBed bed = new RoomBed();
                        bed.br_bed_num = bedroom.BedIndex;
                        drroom.beds.Add(bed);
                        bedroom.TheDriver = driver;
                        driver.IshasRoom = true;
                        break;
                    }
                    

                }
                List<YBDriver> lstLastNoRoomDriver = new List<YBDriver>(DriverList.ToList()).FindAll(delegate(YBDriver info)
                {
                    if (info.IshasRoom == false)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                });

                if (lstLastNoRoomDriver.Count > 0)
                {
                    List<string> lst = new List<string>();
                    lst.Add("以下司机未安排到房间：");
                    foreach (YBDriver noRoomDriver in lstLastNoRoomDriver)
                    {
                        lst.Add(noRoomDriver.DriverName);
                    }
                    MessageBoxHelper.ShowError(lst);
                }

        }
        /// <summary>
        /// 
        /// </summary>
        private void SetRoom2()
        {
            InitBedRoom();
            Dictionary<string, List<YBDriver>> combineDic = new Dictionary<string, List<YBDriver>>();

            foreach (var driver in DriverList)
            {
                if (UnarrangeDriverList.Contains(driver))
                    continue;
                List<YBDriver> dl;
                //区分性别
                string key = driver.Sex == "男" ? driver.driverCommandID + 'M' : driver.driverCommandID + 'F';
                if (combineDic.ContainsKey(key))
                {
                    dl = combineDic[key];
                }
                else
                {
                    dl = new List<YBDriver>();
                    combineDic.Add(key, dl);
                }
                dl.Add(driver);
            }
            arrangeMinDTRoom1(combineDic.Values.ToList());


        }
        /// <summary>
        /// 
        /// </summary>
        private void SetRoom1()
        {
            InitBedRoom();
            Dictionary<string, List<YBDriver>> combineDic = new Dictionary<string, List<YBDriver>>();
            
            foreach (var driver in DriverList)
            {
                List<YBDriver> dl;
                //区分性别
                string key = driver.Sex == "男" ? driver.driverCommandID + 'M' : driver.driverCommandID + 'F';
                if (combineDic.ContainsKey(key))
                {
                    dl = combineDic[key];
                }
                else
                {
                    dl = new List<YBDriver>();
                    combineDic.Add(key, dl);
                }
                dl.Add(driver);
            }
            ////这个List装载不能安排进同一房间的司机组
            List<YBDriver> unarrangedDriverList = new List<YBDriver>();
            ////var tmpList = combineDic.Values.ToList();

            //Dictionary<string, List<List<YBDriver>>> timeDic = new Dictionary<string, List<List<YBDriver>>>();
            //foreach (List<YBDriver> dlist in combineDic.Values)
            //{
            //    string dutyTime = dlist[0].DutyTime;
            //    if (!string.IsNullOrEmpty(dutyTime))
            //    {
            //        string key = dutyTime.Split(':')[0] + dlist[0].Sex;
            //        if (timeDic.ContainsKey(key))
            //            timeDic[key].Add(dlist);
            //        else
            //        {
            //            List<List<YBDriver>> lllist = new List<List<YBDriver>>();
            //            lllist.Add(dlist);
            //            timeDic.Add(key, lllist);
            //        }
            //    }
            //    else
            //    {
            //        string key = dlist[0].Sex;
            //        if (timeDic.ContainsKey(key))
            //            timeDic[key].Add(dlist);
            //        else
            //        {
            //            List<List<YBDriver>> lllist = new List<List<YBDriver>>();
            //            lllist.Add(dlist);
            //            timeDic.Add(key, lllist);
            //        }
            //    }
            //}
            //int timeIndex = 0;
            //var timelist = timeDic.Values.ToList();
            //var tmpList = new List<List<YBDriver>>();

            //while (timelist.Count > 0)
            //{

            //    var list = PopCombine(timelist[timeIndex % timelist.Count]);
            //    if (list != null)
            //    {
            //        tmpList.Add(list);
            //    }
            //    else
            //    {
            //        timelist.Remove(timelist[timeIndex % timelist.Count]);
            //    }
            //    timeIndex++;
            //}



            //List<YBDriver>[] combineList = new List<YBDriver>[tmpList.Count];
            //记录已经安排的房间数，如果已安排的房间数大于房间数，那么进行第二轮筛选
            int arrangedRoomCount = 0;
            var bedRoomDetails = BedRoomsDetails.ToList();
            foreach (List<YBDriver> dlist in combineDic.Values)
            //for (int index = 0; index < tmpList.Count; index++)
            {
                //var dlist = tmpList[index];
                bool arranged = false;
                if (arrangedRoomCount < lstDriverRoom.Count)
                {

                    for (int i = 0; i < lstDriverRoom.Count; i++)
                    {
                        DriverRoom room = lstDriverRoom[i];
                        //判断房间是否已被安排，如果还没安排则对房间进行安排，否则对下一组司机进行安排
                        if (room.br_bed_num == 0 && dlist[0].Sex == room.br_sex)
                        {
                            List<BedRoomObject> brlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == room.br_name; });
                            arrangeCombineRoom(dlist, brlist, room);
                            arrangedRoomCount++;
                            arranged = true;
                            break;
                        }
                    }

                    #region
                    for (int i = 0;!arranged&& i < lstDriverRoom.Count; i++)
                    {
                        DriverRoom room = lstDriverRoom[i];
                        if (dlist.Count <= room.br_bed_avai - room.br_bed_num && dlist[0].Sex == room.br_sex)
                        {
                            List<BedRoomObject> brlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == room.br_name; });
                            arrangeCombineRoom(dlist, brlist, room);
                            arranged = true;
                            break;
                        }
                    }
                    if (!arranged)
                        unarrangedDriverList.AddRange(dlist);
                    #endregion
                    //arrangeMinDTRoom(arranged, bedRoomDetails, dlist, unarrangedDriverList);
                }
                else
                {
                    //将未安排组进行安排
                    //循环所有房间，判断符合组人数而且起床时间最接近的组安排在同一房间
                    #region
                    for (int i = 0; i < lstDriverRoom.Count; i++)
                    {
                        DriverRoom room = lstDriverRoom[i];
                        if (dlist.Count <= room.br_bed_avai - room.br_bed_num && dlist[0].Sex == room.br_sex)
                        {
                            List<BedRoomObject> brlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == room.br_name; });
                            arrangeCombineRoom(dlist, brlist, room);
                            arranged = true;
                            break;
                        }
                    }
                    if (!arranged)
                        unarrangedDriverList.AddRange(dlist);
                    #endregion
                    //arrangeMinDTRoom(arranged, bedRoomDetails, dlist, unarrangedDriverList);
                }

            }
            //这里将组打散安排入宿
            for (int i = 0; i < unarrangedDriverList.Count; i++)
            {
                YBDriver driver = unarrangedDriverList[i];
                for (int p = 0; p < lstDriverRoom.Count; p++)
                {

                    DriverRoom room = lstDriverRoom[p];
                    List<BedRoomObject> brlist = bedRoomDetails.FindAll(delegate(BedRoomObject bro) { return bro.RoomName == room.br_name; });
                    if (room.br_bed_avai > room.br_bed_num && room.br_sex == driver.Sex)
                    {
                        RoomBed bed = new RoomBed();
                        bed.br_bed_num = brlist[room.br_bed_num].BedIndex;
                        brlist[room.br_bed_num].TheDriver = driver;
                        room.beds.Add(bed);

                        driver.IshasRoom = true;
                        room.br_bed_num++;
                        break;
                    }
                }
            }
            List<YBDriver> lstLastNoRoomDriver = new List<YBDriver>(DriverList.ToList()).FindAll(delegate(YBDriver info)
            {
                if (info.IshasRoom == false)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });
            if (lstLastNoRoomDriver.Count > 0)
            {
                List<string> lst = new List<string>();
                lst.Add("以下司机未安排到房间：");
                foreach (YBDriver noRoomDriver in lstLastNoRoomDriver)
                {
                    lst.Add(noRoomDriver.DriverName);
                }
                MessageBoxHelper.ShowError(lst);
            }


        }
        
        private void SetRoom()
        {
            foreach (BedRoomObject bed in BedRoomsDetails)
            {
                bed.TheDriver = null;
            }


            for (int i = 0; i < DriverList.Count; i++)
            {
                YBDriver driver = DriverList[i] as YBDriver;
                if (driver == null)
                    continue;
                if (driver.Sex == "女")
                {
                    for (int k = 0; k < BedRoomsDetails.Count; k++)
                    {
                        if (BedRoomsDetails[k].RoomType == "女" && BedRoomsDetails[k].TheDriver == null)
                        {
                            //查找这个房间的入住信息
                            DriverRoom drroom = lstDriverRoom.Find(delegate(DriverRoom room) { return room.br_name == BedRoomsDetails[k].RoomName; });
                            if (drroom != null)
                            {
                                #region
                                ////判断这房间已经住了几组司机
                                ////只住1组的话直接加入
                                ////两组的话判断是否和当前司机是同一组的

                                //    if (drroom.ListDriverComand.Count==0||drroom.ListDriverComand.Contains(driver.driverCommandID))
                                //    {
                                //        drroom.ListDriverComand.Add(driver.driverCommandID);
                                //        RoomBed bed = new RoomBed();
                                //        bed.br_bed_num = BedRoomsDetails[k].BedIndex;
                                //        drroom.beds.Add(bed);
                                //        BedRoomsDetails[k].TheDriver = driver;
                                //        break;
                                //    }
                                #endregion
                                if (!drroom.ListDriverComand.Contains(driver.driverCommandID))
                                {
                                    //没有包含当前司机组
                                    //判断当前司机组是否能够入住这个房间
                                    if (drroom.br_bed_num + driver.driverTotal <= drroom.br_bed_avai)
                                    {
                                        //可以入住
                                        //增加组id 并且更改当前已入住人数
                                        drroom.ListDriverComand.Add(driver.driverCommandID);
                                        drroom.br_bed_num = drroom.br_bed_num + driver.driverTotal;
                                        RoomBed bed = new RoomBed();
                                        bed.br_bed_num = BedRoomsDetails[k].BedIndex;
                                        drroom.beds.Add(bed);
                                        BedRoomsDetails[k].TheDriver = driver;
                                        driver.IshasRoom = true;
                                        break;

                                    }
                                }
                                else
                                {
                                    //包含当前司机组
                                    RoomBed bed = new RoomBed();
                                    bed.br_bed_num = BedRoomsDetails[k].BedIndex;
                                    drroom.beds.Add(bed);
                                    BedRoomsDetails[k].TheDriver = driver;
                                    driver.IshasRoom = true;
                                    break;

                                }


                            }
                            else
                            {
                                BedRoomsDetails[k].TheDriver = driver;
                                driver.IshasRoom = true;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    for (int k = 0; k < BedRoomsDetails.Count; k++)
                    {
                        if (BedRoomsDetails[k].RoomType == "男" && BedRoomsDetails[k].TheDriver == null)
                        {
                            //查找这个房间的入住信息
                            DriverRoom drroom = lstDriverRoom.Find(delegate(DriverRoom room) { return room.br_name == BedRoomsDetails[k].RoomName; });
                            if (drroom != null)
                            {
                                //判断这房间已经住了几组司机
                                //只住1组的话直接加入
                                //两组的话判断是否和当前司机是同一组的
                                #region
                                /*  if (drroom.ListDriverComand.Count <= 1)
                                {
                                    if (!drroom.ListDriverComand.Contains(driver.driverCommandID))
                                    {
                                        drroom.ListDriverComand.Add(driver.driverCommandID);
                                        RoomBed bed = new RoomBed();
                                        bed.br_bed_num = BedRoomsDetails[k].BedIndex;
                                        drroom.beds.Add(bed);
                                    }
                               
                                    BedRoomsDetails[k].TheDriver = driver;
                                    break;
                                }
                                else
                                {
                                    if (drroom.ListDriverComand.Contains(driver.driverCommandID))
                                    {
                                        RoomBed bed = new RoomBed();
                                        bed.br_bed_num = BedRoomsDetails[k].BedIndex;
                                        drroom.beds.Add(bed);
                                        BedRoomsDetails[k].TheDriver = driver;
                                        break;
                                    }
                                }*/
                                #endregion

                                //先判断是否有这个司机组，有直接插入 ，没有 计算看还能不能插入一组司机

                                if (!drroom.ListDriverComand.Contains(driver.driverCommandID))
                                {
                                    //没有包含当前司机组
                                    //判断当前司机组是否能够入住这个房间
                                    if (drroom.br_bed_num + driver.driverTotal <= drroom.br_bed_avai)
                                    {
                                        //可以入住
                                        //增加组id 并且更改当前已入住人数
                                        drroom.ListDriverComand.Add(driver.driverCommandID);
                                        drroom.br_bed_num = drroom.br_bed_num + driver.driverTotal;
                                        RoomBed bed = new RoomBed();
                                        bed.br_bed_num = BedRoomsDetails[k].BedIndex;
                                        drroom.beds.Add(bed);
                                        BedRoomsDetails[k].TheDriver = driver;
                                        driver.IshasRoom = true;
                                        break;

                                    }
                                }
                                else
                                {
                                    //包含当前司机组
                                    RoomBed bed = new RoomBed();
                                    bed.br_bed_num = BedRoomsDetails[k].BedIndex;
                                    drroom.beds.Add(bed);
                                    BedRoomsDetails[k].TheDriver = driver;
                                    driver.IshasRoom = true;
                                    break;

                                }


                            }
                            else
                            {
                                BedRoomsDetails[k].TheDriver = driver;
                                driver.IshasRoom = true;
                                break;
                            }
                        }
                        // lstYBNoRoomDriver.Add(driver);
                    }
                }

                //没有跳出循环的司机记录下来

            }


            //到最后还没有分到房间的司机
            List<YBDriver> lstYBNoRoomDriver = new List<YBDriver>(DriverList.ToList()).FindAll(delegate(YBDriver info)
            {
                if (info.IshasRoom == false)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });
            //查找没有分到组的司机
            //lstYBNoRoomDriver=
            foreach (YBDriver dy in lstYBNoRoomDriver)
            {
                if (dy.Sex == "女")
                {
                    for (int k = 0; k < BedRoomsDetails.Count; k++)
                    {
                        if (BedRoomsDetails[k].RoomType == "女" && BedRoomsDetails[k].TheDriver == null)
                        {
                            BedRoomsDetails[k].TheDriver = dy;
                            dy.IshasRoom = true;
                            break;
                        }
                    }
                }
                else
                {
                    for (int k = 0; k < BedRoomsDetails.Count; k++)
                    {
                        if (BedRoomsDetails[k].RoomType == "男" && BedRoomsDetails[k].TheDriver == null)
                        {
                            BedRoomsDetails[k].TheDriver = dy;
                            dy.IshasRoom = true;
                            break;
                        }
                        //lstLastNoRoomDriver.Add(dy);
                    }
                }


            }
            //  List<YBDriver> lstLastNoRoomDriver = new List<YBDriver>();
            List<YBDriver> lstLastNoRoomDriver = new List<YBDriver>(DriverList.ToList()).FindAll(delegate(YBDriver info)
            {
                if (info.IshasRoom == false)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });
            if (lstLastNoRoomDriver.Count > 0)
            {
                List<string> lst = new List<string>();
                lst.Add("以下司机未安排到房间：");
                foreach (YBDriver noRoomDriver in lstLastNoRoomDriver)
                {
                    lst.Add(noRoomDriver.DriverName);
                }
                MessageBoxHelper.ShowError(lst);
            }

        }

        private bool InitYbDriverList()
        {
            DriverList.Clear();
            UnarrangeDriverList.Clear();

            int tableID = -1;
            if (!CheckCanSelectDriver(ref tableID))
                return false;

            DataTable YBDriverDT = _bedRoomaccess.GetYBDrivers(tableID);

            if (null == YBDriverDT || YBDriverDT.Rows.Count < 1)
                return false;

            DataRow[] YbRows = YBDriverDT.Select();

            for (int i = 0; i < YbRows.Length; i++)
            {
                YBDriver driver = new YBDriver();
                driver.DriverName = YbRows[i]["userName"].ToString();
                driver.Sex = YbRows[i]["sex"].ToString();
                driver.DutyTime = YbRows[i]["DutyTime"].ToString();
                driver.driverCommandID = YbRows[i]["dcom_id"].ToString();
                driver.driverTotal = Convert.ToInt32(YbRows[i]["Total"].ToString());
                if (!string.IsNullOrEmpty(driver.DutyTime))
                {
                    driver.CallTime = GlobalVariables.FormatTime((GlobalVariables.FormatTimeToInt(driver.DutyTime) - Convert.ToInt32(CallHeadMin) * 60).ToString());
                    driver.CallTime = driver.CallTime.Substring(0, 6) + "00";

                }

                DriverList.Add(driver);
            }
            
            return true;
        }

        public bool CheckCanSelectDriver(ref int tableID)
        {
            bool hasCrossRoadRecord = _driverTeamAccess.CheckHasRefreshCrossRoad();
            hasCrossRoadRecord = true;

            if (!hasCrossRoadRecord)
            {
                MessageBoxHelper.ShowError("获取今天夜班司机信息失败：请先执行今天的加载出退勤信息操作后重试！");
                return false;
            }

            string tableName = "";
            string tomorrow = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
            if (!_driverTeamAccess.CheckHasTimeTableToDate(ref tableID, ref tableName, tomorrow))
            {
                MessageBoxHelper.ShowError(string.Format("获取{0}早班信息失败，请点击主界面“安排时刻表到日期”进行次日时刻表配置！", tomorrow));
                return false;
            }
            else if (!_driverTeamAccess.CheckHasCrossRoad(tableID))
            {
                MessageBoxHelper.ShowError(string.Format("获取时刻表：{0} 的交路表早班信息失败，请先执行【生成出勤表】功能并保存！", tableName));
                return false;
            }

            return true;
        }

        #region 非早班司机加入公寓的逻辑

        public void AddNotMorDriverCommand_Method()
        {
            if (SelectedDate != DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"))
            {
                MessageBoxHelper.ShowError("请选择正确日期后重试！（添加添加司机功能仅限于今天）");
                return;
            }

            if (string.IsNullOrEmpty(DName))
            {
                MessageBoxHelper.ShowError("请输入司机姓名！");
                return;
            }

            if (null == SelectedRoom || BedIndex < 1)
            {
                MessageBoxHelper.ShowError("请选择房间号及床位号！");
                return;
            }

            _dutyTime = BedRoomsView.GetInstances().GetDutyTime();

            _callTime = BedRoomsView.GetInstances().GetCallTime();

            if (string.IsNullOrEmpty(_dutyTime) || string.IsNullOrEmpty(_callTime))
            {
                MessageBoxHelper.ShowError("请选择出勤时间或叫醒时间！");
                return;
            }

            if (_callTime.CompareTo(_dutyTime) >= 0)
            {
                MessageBoxHelper.ShowError("叫醒时间必须提前于出勤时间，请确认！");
                return;
            }

            YBDriver newDriver = new YBDriver();
            newDriver.DriverName = DName;
            newDriver.CallTime = _callTime;
            newDriver.DutyTime = _dutyTime;

            for (int k = 0; k < BedRoomsDetails.Count; k++)
            {
                if (BedRoomsDetails[k].RoomName == SelectedRoom.RoomName && BedRoomsDetails[k].BedIndex == BedIndex.ToString())
                {
                    if (BedRoomsDetails[k].TheDriver == null)
                        BedRoomsDetails[k].TheDriver = newDriver;
                    else if (MessageBoxHelper.ConfirmYesNo(string.Format("房间号：{0},床位号:{1} 已安排司机 {2} 入住，是否进行替换？",
                                                                SelectedRoom.RoomName,
                                                                BedIndex.ToString(),
                                                                BedRoomsDetails[k].TheDriver.DriverName)
                                                                )
                        )
                    {
                        BedRoomsDetails[k].TheDriver = newDriver;
                    }
                }
            }



        }

        #endregion

        /// <summary>
        /// 取消叫班
        /// </summary>
        /// <param name="name"></param>
        /// <param name="time"></param>
        public bool CancelCall(string name, string time)
        {
            return _bedRoomaccess.CancelCall(name, time);
        }
        public bool CancelCall(BedRoomObject bed)
        {
            string name=bed.TheDriver.DriverName;
            string time = Convert.ToDateTime(bed.TheDriver.DutyTime).ToString("HH:mm");
            informDT = _bedRoomaccess.GetInform(DateTime.Now);
            DataRow[] rows = informDT.Select("Callvoice like '%" + name + "%'  and callvoice like '%" + time + "%'");
            if (rows.Length > 0)
            {
                bed.CanCelCall = BedRoomObject.CANCELED;
                rows[0]["deleted"] = 1;
            }
            return _bedRoomaccess.CancelCall(name, time);
        }
    }

}
